<template>

  <div class="siting">


    <!-- tit -->
    <div class="main-icon">
      <div class="main-icon-a">
        <i :class="iconComes"
           style="border-radius: 50%;font-size: 20px;padding: 6px;margin-left: 5px;;background-color: #5a5a5a;color: #fff;"></i>
        <span
            style="font-size: 14px;font-weight:bold;margin-left: 12px;color: #606266;display: inline-block;width: 88px;">{{
            CatalogueName
          }}</span>
      </div>

      <!-- btn2 -->
<!--      <div class="main-icon-c">
        <span
            style="font-size: 14px;color: #606266;font-weight: bold;display: inline-block;width: 70px;">排班方式：</span>
        <el-select v-model="selectedValue" filterable placeholder="请选择" size="mini" @change="handleDutyModeChange"
                   clearable>
          <el-option
              v-for="item in dutyModeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </div>-->
      <!-- btn1 -->
      <div class="main-icon-zzgl">
        <span style="font-size: 14px;color: #606266;font-weight: bold;margin-left: 12px;">有效状态：</span>
        <el-dropdown @command="handleCommand" trigger="click">
          <span class="el-dropdown-link">{{ DropDownedName }}<i class="el-icon-down"></i></span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="a">已审</el-dropdown-item>
            <el-dropdown-item command="b">待审</el-dropdown-item>
            <el-dropdown-item command="c">作废</el-dropdown-item>
            <el-dropdown-item command="d" divided>全部</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>


      <div class="feet">
        <el-button v-for="(v,i) in feetBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini" plain
                   v-if="!v.auth || permissionsArr.includes(v.auth)"
                   @click="feetHandClick(i)">{{ v.title }}
        </el-button>
      </div>
    </div>
    <!-- table -->
    <div class="homeTable">
      <el-table :data="tableData" border @row-click="handledbRow" @row-dblclick="handleRowDblClick"
                style="width:100%"
                @selection-change="handleSelectionChange" highlight-current-row>
        <!-- fixed -->

        <el-table-column align="center" v-for="(col, inx) in tableRows" :key="inx" :type="col.type" :prop="col.prop"
                         :label="col.name" :render-header="labelHead"
                         :min-width="getColumnWidth(col.label,col.prop,tableData)">
          <template #default="{ row }">
            {{ safeGetMappedValue(col, row) }}
          </template>
        </el-table-column>
        <el-table-column fixed="left" label="行号" type="index" width="68" align="center"></el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[8, 16, 24]"
          :page-size="pageSize"
          :total="totalSize"
          layout="total, sizes, prev, pager, next, jumper"
          background>
        >
      </el-pagination>
    </div>

    <el-dialog
        title="排班明细"
        :visible.sync="schedulingDialogVisible"
        width="90%"
        custom-class="schedule-dialog"
        @close="closeScheduling">

      <!-- 顶部筛选区域 -->
      <div class="filter-row">
        <div class="filter-item">
          <span class="filter-label">生效时间:</span>
          <el-date-picker
              :disabled="state === 3"
              v-model="rowData.startTime"
              type="date"
              placeholder="选择月份"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              @change="updateDateColumns"
              :editable="false"
              style="width: 150px"
              size="mini">
          </el-date-picker>
        </div>

        <div class="filter-item">
          <span class="filter-label">失效时间:</span>
          <el-date-picker
              :disabled="state === 3"
              size="mini"
              v-model="rowData.endTime"
              type="date"
              placeholder="选择日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              :editable="false"
              style="width: 150px">
          </el-date-picker>
        </div>

        <div class="filter-item">
          <span class="filter-label">科室:</span>
          <el-select
              size="mini"
              v-model="selDeptOrDoctor.deptId"
              placeholder="请选择科室"
              @focus="getDeptList"
              @change="getDataByDeptId"
              clearable
              style="width: 150px">
            <el-option
                v-for="item in deptOptions"
                :key="item.id"
                :label="item.deptName"
                :value="item.id">
            </el-option>
          </el-select>
        </div>

        <div class="filter-item">
          <span class="filter-label">医生:</span>
          <el-select
              size="mini"
              v-model="selDeptOrDoctor.doctorId"
              placeholder="请选择医生"
              @focus="getDoctorList()"
              @change="getDataByDoctor"
              clearable
              style="width: 150px">
            <el-option
                v-for="item in doctorOptions"
                :key="item.id"
                :label="item.fullName"
                :value="item.id">
            </el-option>
          </el-select>
        </div>
      </div>

      <div class="divider-line"></div>

      <!-- 双表格容器 -->
      <div class="dual-table-container">
        <!-- 主表格 -->
        <div class="main-table" :style="{width: tabelController ? '70%' : '100%'}">
          <el-table
              ref="tableRef"
              :data="tableData2"
              border
              :span-method="objectSpanMethod"
              :row-style="handleRowStyle"
              :cell-class-name="handleCellClass"
              @row-click="handleClickRow"
              @row-dblclick="handleRowDoubleClick"
              height="480px"
              :header-cell-style="{ height: '48px', padding: '4px 0' }"
          >

            <el-table-column fixed="left" label="行号" type="index" width="50" align="center"></el-table-column>
            <el-table-column
                v-for="(col, inx) in tableRows2"
                :key="inx"
                :type="col.type"
                :prop="col.prop"
                :label="col.name"
                :resizable="true"
                fixed="left"
                align="center"
                :render-header="labelHead"
                :min-width="getColumnWidth(col.label,col.prop,tableData2)">
            </el-table-column>

            <el-table-column
                v-for="(day, index) in dateColumns"
                :key="'day_' + index"
                :prop="day.label"
                :label="day.label"
                width="80"
                align="center"
                >
              <template slot="header">
                <div>{{ day.label }}</div>
                <div class="weekday">{{ day.weekday }}</div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 详情表格（右侧） -->
        <div class="detail-table" v-show="tabelController">
          <el-table
              :header-cell-style="{ height: '55px', padding: '4px 0' }"
              :data="tableData4"
              border
              height="480px"
              empty-text="点击左侧表格行查看详情">

            <el-table-column
                type="index"
                label="行号"
                width="60"
                align="center">
            </el-table-column>

            <el-table-column
                v-for="(col, inx) in tableRows3"
                :key="inx"
                :type="col.type"
                :prop="col.prop"
                :label="col.name"
                align="center">
            </el-table-column>
          </el-table>

        </div>
      </div>

      <div class="divider-line"></div>

      <!-- 底部控制栏 -->
      <div class="dialog-footer">
        <div class="footer-controls">
          <div class="info-items">
          <span>排班人:
            <el-input
                v-model="rowData.staffName"
                disabled
                size="mini"
                style="width: 100px; margin-left: 0;font-size: 13px;">
            </el-input>
          </span>
            <span style="margin-left:10px">排班时间:
            <el-input
                v-model="rowData.operationTime"
                disabled
                size="mini"
                style="width: 100px; margin-left: 0;font-size: 13px">
            </el-input>
          </span>
            <span style="margin-left:10px">审核人:
            <el-input
                v-model="rowData.exaStaffName"
                disabled
                size="mini"
                style="width: 100px; margin-left: 0;font-size: 13px;">
            </el-input>
          </span>
            <span style="margin-left:10px">审核时间:
            <el-input
                v-model="rowData.exaTime"
                disabled
                size="mini"
                style="width: 100px; margin-left: 0;font-size: 13px">
            </el-input>
          </span>

            <template>
              <div v-show="state === 3">
                <span style="margin-left:10px">显示明细:
                  <el-checkbox
                      :value="tabelController"
                      @change="val => tabelController = val"
                      size="mini">
                  </el-checkbox>
                </span>
              </div>
            </template>
          </div>

          <div class="action-items">
            <div class="action-buttons" v-show="state !== 3">
              <el-button type="success" size="mini" @click="addScheduling">保存</el-button>
              <el-button type="danger" size="mini" @click="closeScheduling">取消</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <el-dialog
        title="编辑排班明细数据"
        :visible.sync="editDialogVisible"
        width="70%"
        @close="closeSchedulingDetail"
        custom-class="schedule-dialog">

      <!-- 顶部信息栏（匹配图片） -->
      <div class="info-header" style="margin-top: -20px;">
        <span style="margin-left:10px">科室:
          <el-input
              v-model="editDeptOrDoctor.deptName"
              :disabled="true"
              placeholder="系统自动获取"
              size="mini"
              style="width: 100px; margin-left: 0;font-size: 13px;"
              class="disabled-input"
          ></el-input>
          </span>
        <span style="margin-left:15px">医生:
          <el-input
              v-model="editDeptOrDoctor.doctorName"
              :disabled="true"
              placeholder="系统自动获取"
              size="mini"
              style="width: 100px; margin-left: 0;font-size: 13px;"
              class="disabled-input"
          ></el-input>
          </span>
      </div>

      <div class="divider-line"></div> <!-- 分隔线 -->

      <el-table :data="tableData3" border style="width: 100%" height="60vh">
        <!-- 固定列 -->
        <el-table-column
            prop="rowNum"
            label="行号"
            width="80"
            fixed="left"
            align="center">
        </el-table-column>

        <el-table-column
            align="center"
            prop="description"
            label="说明"
            width="150"
            fixed="left">
        </el-table-column>

        <el-table-column
            v-for="(day, index) in dateColumns"
            :key="'day_' + index"
            :prop="day.prop"
            :label="day.label"
            width="80"
            align="center">

          <template slot="header">
            <div>{{ day.label }}</div> <!-- 日期 -->
            <div class="weekday">{{ day.weekday }}</div> <!-- 星期 -->
          </template>


          <template slot-scope="{row, $index}">
            <!-- 如果 description 是 "上午"、"下午"、"晚上"，显示复选框 -->
            <el-checkbox
                v-if="['上午', '下午', '晚班'].includes(row.description)"
                v-model="day[row.rowNum === 1 ? 'am' :
                     row.rowNum === 2 ? 'pm' : row.rowNum === 3 ? 'night' :'']"
                @change="handleCheckboxChange(row, day)"
                size="mini"
            ></el-checkbox>

            <!-- 否则显示数字输入框 -->
            <el-input
                type="text"
                v-else
                v-model="day[
                        row.rowNum === 4 ? 'amLimit' :
                        row.rowNum === 5 ? 'pmLimit' :
                        row.rowNum === 6 ? 'nightLimit' :
                        row.rowNum === 7 ? 'limitRestrict' :
                        row.rowNum === 8 ? 'limitNo' :
                        row.rowNum === 9 ? 'netLimit' :
                        row.rowNum === 10 ? 'otherLimit' : '' ]"
                oninput="this.value=this.value.replace(/[^\d]/g,'').slice(0, 2)"
                :disabled="day.isTrue"
                @input="handleInputChange(row, day)" @change="handleInputFocus(row,day)"
            ></el-input>
          </template>
        </el-table-column>
      </el-table>
      <div class="divider-line"></div> <!-- 分隔线 -->
<!--      <div style="float: left;" v-show="state !== 3">
        <el-button type="warning" size="small" @click="onCheckAllDay">全选</el-button>
        <el-button type="danger" size="small" @click="offCheckAllDay">全不选</el-button>
      </div>-->
      <div style="float: right;" v-show="state !== 3">
        <el-button type="success" size="mini" @click="addSchedulingDetail">保存</el-button>
        <el-button type="danger" size="mini" @click="closeSchedulingDetail">取消</el-button>
      </div>
      <div style="clear: both;"></div>
    </el-dialog>
    <!-- 分页 -->

    <!-- feet -->
  </div>
</template>

<script>
import {
  addScheduling,
  checkScheduling,
  editScheduling,
  getActiveList,
  getDeptList,
  getDoctorDateList,
  getDoctorList,
  getSchedulingData,
  getSchedulingDtail
} from "@/api/scheduling/scheduling";
import dayjs from "dayjs";
import {usersList} from "@/api/user";
import {withLoading} from "@/untils/loading";

export default {
  data() {
    return {
      // str
      iconComes: 'el-icon-zzgl',
      CatalogueName: '坐诊排班',
      DropDownedName: '全部',
      selectedValue: 1,
      userInfo: [],
      // blean
      loading: false,
      // number
      pageNum: 1, //当前页currentPage
      pageSize: 8,
      totalSize: 10, //总条数
      numericValue: null,


      tabelController: false,
      checkedItems: [],
      schedulingDialogVisible: false,
      editDialogVisible: false,
      highlightedCell: null,
      lastMonthCount: 278,
      selDeptOrDoctor: {
        deptId: null,
        doctorId: null
      },
      editDeptOrDoctor: {
        deptId: null,
        deptName: "",
        doctorName: "",
        registertypeId: null,
        registertypeName: '',
        id: null,
      },
      addSchedulingForm: {
        id: null,
        dutyMent: 1,
        dutyMode: 1,
        dutyStatus: 0,
        dutyType: 0,
        endTime: "",
        name: "",
        startTime: "",
        detailsDTOList: [],
      },

      addForm: {
        detailsDTOList: [{
          am: null,
          amLimit: null,
          deptId: null,
          limitNo: null,
          limitRestrict: null,
          netLimit: null,
          night: null,
          nightLimit: null,
          otherLimit: null,
          pm: null,
          pmLimit: null,
          rgstTypeId: null,
          utyDate: '',
          weekNo: null
        }],
        dutyMent: "",
        dutyMode: null,
        dutyStatus: null,
        dutyType: null,
        endTime: "",
        name: "",
        rgstId: null,
        startTime: ""
      },
      selectedMonth: '', // 保存选择的月份（格式：yyyy-MM）
      deptOptions: [],
      doctorOptions: [],
      userOptions: [],
      isDatePickerDisabled: false,

      feetBtn: [
        //{refesh: "refesh", title: "刷新", type: "primary", icon: "el-icon-refresh"},
        {refesh: "refesh", title: "排班", type: "primary",auth:'system:dutytable:add'},
        {refesh: "refesh", title: "修改排班", type: "primary",auth:'system:dutytable:edit'},
        {refesh: "refesh", title: "审核", type: "primary",auth:'system:dutytable:check'},
        {refesh: "refesh", title: "作废", type: "primary",auth:'system:dutytable:check'},
        /*{senior: "senior", title: "更新时间明细", type: "primary", icon: "el-icon-refresh"},
        {refesh: "refesh", title: "打印", type: "primary", icon: "el-icon-ggml"},
        {refesh: "refesh", title: "导出", type: "primary", icon: "el-icon-lcyt"},*/
      ],
      dutyModeOptions: [{value: 0, label: '星期排班'}, {value: 1, label: '按月排班'}],
      dutyMentNameOptions: [{id: 1, label: '临时'}, {id: 2, label: '长期'}],
      stateOptions: [{id: 0, label: '待审'}, {id: 1, label: '已审'}, {id: 2, label: '作废'}],
      tableRows: [
        //{name: "系统序号", prop: "id", nz: "nz"},
        {name: "排班性质", prop: "dutyMentName", type: "", op: 'dutyMentNameOptions'}, {
          name: "排班名称",
          prop: "name",
          type: ""
        },
        {name: "排班开始时间", prop: "startTime", type: ""}, {
          name: "排班结束时间",
          prop: "endTime",
          type: ""
        }, {name: "排班状态", prop: "dutyStatus", op: 'stateOptions'},
        {name: "审核人", prop: "exaStaffName"}, {name: "审核时间", prop: "exaTime", type: ""},
        {name: "排班人", prop: "staffName", op: ''}, {name: "排班操作时间", prop: "operationTime", type: ""}
      ],
      tableRows2:
          [{name: "系统序号", prop: "id", nz: "nz"}, {name: "科室序号", prop: "deptId", type: ""},
            {name: "科室名称", prop: "deptName", type: ""}, {name: "挂号类别", prop: "registertypeName", type: ""},{name: "医生名称", prop: "doctorName", type: ""}],

      tableRows3: [
        {name: "有效状态", prop: "state", nz: "nz"}, {name: "开始时间", prop: "beinTime", type: ""},
        {name: "结束时间", prop: "endTime", type: ""}, {name: "限号数量", prop: "limitNo", type: ""},
        {name: "限约数量", prop: "limitRestrict", type: ""}, {name: "排班时段", prop: "timeSpan", type: ""},
        {name: "网约", prop: "netB", type: ""}
      ],
      rowData: {
        startTime: dayjs().startOf('day').format('YYYY-MM-DD 00:00:00'),
        endTime: dayjs().endOf('month').format('YYYY-MM-DD 23:59:59'),
      },
      rowEditData: {},
      tableData: [],
      multipleSelection: [], //table 多选组
      tableData2: [],
      tableData4: [],
      state: null,
      tableData3: [
        {rowNum: 1, description: '上午'},
        {rowNum: 2, description: '下午'},
        {rowNum: 3, description: '晚班'},
        {rowNum: 4, description: '上午限号数'},
        {rowNum: 5, description: '下午限号数'},
        {rowNum: 6, description: '晚班限号数'},
        {rowNum: 7, description: '限约'},
        {rowNum: 8, description: '限号'},
        {rowNum: 9, description: '微信限号数'},
        {rowNum: 10, description: '其他预约数量'}
      ],
      spanMap: [],
      permissionsArr:[],
      dateColumns: [],    // 日期列配置
      currentMonth: null,  // 当前处理月份
      detailsDTOList: [],
      clickedRow: null,    // 记录被点击的行索引
      clickedCol: null,
      limitArr: ['am', 'pm', 'night', 'amLimit', 'pmLimit', 'limitNo', 'limitRestrict', 'netLimit', 'nightLimit', 'otherLimit'],
    }
  },
  mounted() {
    this.userInfo = JSON.parse(localStorage.getItem('userInfo'));
    this.loadData();
    this.permissionsArr = JSON.parse(localStorage.getItem('permissions'))
    this.getDoctorList();
    this.$nextTick(() => {
      this.updateWindowWidth();
      window.addEventListener('resize', this.updateWindowWidth);
    })
  },
  methods: {

    // 行高亮逻辑
    handleRowStyle({row, rowIndex}) {
      return rowIndex === this.clickedRow
          ? {background: '#ecf5ff'}
          : {};
    },

    // 单元格高亮逻辑
    handleCellClass({row, column, rowIndex}) {
      if (
          rowIndex === this.clickedRow &&
          column.property === this.clickedCol
      ) {
        return 'highlight-cell';
      }
      return '';
    },

    async handleDutyModeChange() {
      const res = await getSchedulingData({
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        state: this.numericValue == null ? null : this.numericValue,
      })
      if (res.code === 200) {
        const dataToProcess = this.selectedValue !== ''
            ? res.data.content.filter(item => item.dutyMode === this.selectedValue)
            : res.data.content;
        this.tableData = dataToProcess.map(item => ({
          ...item,
          username: this.userInfo.username,
          startTime: item.startTime ? item.startTime.split(' ')[0] : null,
          endTime: item.endTime ? item.endTime.split(' ')[0] : null,
          dutyMentName: item.dutyMent === "1" ? "临时" : "长期",
          state: item.dutyStatus === 0 ? "待审" : item.dutyStatus === 1 ? "已审" : "作废"
        }));
        this.pageNum = res.data.pageNum
        this.pageSize = res.data.pageSize
        this.totalSize = res.data.totalSize
      }
    },

    async addScheduling() {
      if (!this.rowData.startTime || !this.rowData.endTime) {
        this.$message.error('请选择完整的开始和结束时间');
        return;
      }

      await withLoading(this, '数据提交中...')(async () => {
        // 使用 Day.js 处理时间
        const startTime = dayjs(this.rowData.startTime);
        let endTime = dayjs(this.rowData.endTime);

        // 检查结束时间是否早于开始时间
        if (endTime.isBefore(startTime)) {
          // 自动修正为开始时间所在月份的最后一天 23:59:59
          endTime = startTime.endOf('month');
          this.rowData.endTime = endTime.format('YYYY-MM-DD HH:mm:ss');
          this.$message.warning('失效时间不能大于生效时间!已自动更正!');
          return;
        }

        // 准备表单数据（保持原有逻辑）
        this.addSchedulingForm.name = `排班表:${dayjs().format('YYYY-MM-DD')}`;
        this.addSchedulingForm.startTime = dayjs(this.rowData.startTime).startOf('day').format('YYYY-MM-DD HH:mm:ss');
        this.addSchedulingForm.endTime = dayjs(this.rowData.endTime).endOf('day').format('YYYY-MM-DD HH:mm:ss');
        this.addSchedulingForm.detailsDTOList = this.detailsDTOList;
        this.addSchedulingForm.dutyStatus = 0;
        this.addSchedulingForm.dutyMent = 1;
        this.addSchedulingForm.dutyMode = this.selectedValue;
        this.addSchedulingForm.dutyType = 0;
        console.log(this.addSchedulingForm,'=====================================================================')
        // 提交逻辑（保持不变）
        if (this.state == null) {
          const res = await addScheduling(this.addSchedulingForm);
          if (res.code === 200) {
            this.schedulingDialogVisible = false;
            this.addSchedulingForm = Object.assign({}, this.$options.data.call(this).addSchedulingForm)
            this.detailsDTOList = [];
            this.state = null;
            this.tabelController = false;
          } else {
            this.$message.error(res.message);
          }
        } else {

          this.addSchedulingForm.id = this.rowEditData.id;
          const res = await editScheduling(this.addSchedulingForm);
          if (res.code === 200) {
            this.schedulingDialogVisible = false;
            this.addSchedulingForm = Object.assign({}, this.$options.data.call(this).addSchedulingForm)
            this.state = null;
            this.detailsDTOList = [];
          } else {
            this.$message.error(res.message);
          }
        }
      });

      await this.loadData();
    },
    closeSchedulingDetail() {
      this.tableData3 = [
        {rowNum: 1, description: '上午'},
        {rowNum: 2, description: '下午'},
        {rowNum: 3, description: '晚班'},
        {rowNum: 4, description: '上午限号数'},
        {rowNum: 5, description: '下午限号数'},
        {rowNum: 6, description: '晚班限号数'},
        {rowNum: 7, description: '限约'},
        {rowNum: 8, description: '限号'},
        {rowNum: 9, description: '微信限号数'},
        {rowNum: 10, description: '其他预约数量'}
      ];

      const tableColumns = new Set();
      this.tableData2.forEach(row => {
        Object.keys(row).forEach(key => tableColumns.add(key));
      });
      this.detailsDTOList = this.detailsDTOList.filter(item =>
          tableColumns.has(item.label)
      );
      this.tableData4 = [];
      this.editDialogVisible = false;
    },
    closeScheduling() {
      this.tableData4 = [];
      this.detailsDTOList = [];
      this.addForm = {};
      this.addSchedulingForm = {};
      this.dateColumns = [];
      this.selDeptOrDoctor = {};
      this.state = null;
      this.tabelController = false;
      this.schedulingDialogVisible = false;
    },

    async addSchedulingDetail() {
      await withLoading(this, '数据提交中...')(async () => {
        for (const val of this.detailsDTOList) {
          const index = this.detailsDTOList.findIndex(item =>
              item.label === val.label && item.id === val.id
          );

          if (index !== -1) {
            this.detailsDTOList[index] = val;
          } else {
            this.detailsDTOList.push(val);
          }

          const item = this.detailsDTOList.find(item =>
              item.label === val.label && item.id === val.id
          );

          // 其他业务逻辑...
          const timeSlots = [];
          if (item.am === 1) timeSlots.push('上午');
          if (item.pm === 1) timeSlots.push('下午');
          if (item.night === 1) timeSlots.push('晚上');
          item.dutyTimeType = this.getScheduleType(timeSlots);
          const isAllDay = item.am === 1 && item.pm === 1 && item.night === 1;
          const rowIndex = this.tableData2.findIndex(item => item.id === val.id);
          this.$set(this.tableData2[rowIndex], item.label, isAllDay ? '全天' : timeSlots.join(''));
          this.addItem(val.label, val.id);
        }

        // 只有所有数据有效时才执行清理和关闭模态框
        this.dateColumns.forEach(item => {
          item.am = null;
          item.pm = null;
          item.night = null;
          item.prop = null;
          item.night = null;
          item.amLimit = null;
          item.pmLimit = null;
          item.nightLimit = null;
          item.limitRestrict = null;
          item.limitNo = null;
          item.netLimit = null;
          item.otherLimit = null;
        })
        this.editDialogVisible = false;
      });
    },

    onCheckAllDay() {
      this.detailsDTOList = [];
      //this.detailsDTOList = [];
      this.dateColumns.forEach(item => {
        item.am = true;
        item.pm = true;
        item.night = true;
        item.isTrue = false;
        this.detailsDTOList.push({
          am: 1,
          pm: 1,
          night: 1,
          weekNo: item.weekNo,
          label: item.label,
          rgstId: this.rowData.id,
          id: this.rowData.id
        })
      })
    },
    offCheckAllDay() {
      this.detailsDTOList = [];
      this.dateColumns.forEach(item => {
        item.am = null;
        item.pm = null;
        item.night = null;
        item.prop = null;
        item.night = null;
        item.amLimit = null;
        item.pmLimit = null;
        item.nightLimit = null;
        item.limitRestrict = null;
        item.limitNo = null;
        item.netLimit = null;
        item.otherLimit = null;
        item.isTrue = true;
      })
      this.detailsDTOList = [];
    },

    addItem(label, id) {
      // 1. 统一转为数字类型比较（根据你的parseInt使用）
      const targetLabel = parseInt(label);
      const targetId = parseInt(id); // 新增：要匹配的id
      if (isNaN(targetLabel)) return; // 无效label过滤

      // 2. 找出所有相同label的对象
      const sameLabelItems = this.detailsDTOList.filter(
          item => parseInt(item.label) === targetLabel && item.id === targetId
      );

      // 3. 检查是否存在相同label且相同id的对象
      const existingItemWithSameId = sameLabelItems.find(
          item => parseInt(item.id) === targetId
      );


      if (existingItemWithSameId) {
        // 4. 如果存在相同id，执行合并逻辑
        const mergedItem = sameLabelItems.reduce((result, current) => ({
          ...result,
          ...current // 后面的对象会覆盖前面的同名属性
        }), {label: targetLabel, id: targetId}); // 确保保留label和id

        // 5. 先移除所有相同label的旧对象
        this.detailsDTOList = this.detailsDTOList.filter(
            item => !(parseInt(item.label) === targetLabel && parseInt(item.id) === targetId)
        );

        // 6. 添加合并后的新对象
        this.detailsDTOList.push(mergedItem);
      } else {
        // 7. 如果没有相同id，直接push新对象
        this.detailsDTOList.push({
          label: targetLabel,
          id: targetId,
          // 其他默认属性...
        });
      }

      // 8. 清理不包含必要字段的对象
      const arr = ['amLimit', 'limitNo', 'limitRestrict', 'netLimit', 'pmLimit', 'am', 'pm', 'night', 'otherLimit', 'nightLimit'];
      for (let i = this.detailsDTOList.length - 1; i >= 0; i--) {
        const item = this.detailsDTOList[i];
        const hasAnyField = arr.some(field => item.hasOwnProperty(field));
        const allFieldsNull = arr.every(field => !item.hasOwnProperty(field) || item[field] === null);
        if (!hasAnyField || allFieldsNull) {
          this.detailsDTOList.splice(i, 1);
        }
      }

      // 9. 升序排序
      this.detailsDTOList.sort((a, b) => {
        const aLabel = parseInt(a.label);
        const bLabel = parseInt(b.label);
        return aLabel - bLabel;
      });


    },
    handleCheckboxChange(row, day) {
      console.log(row, day)
      switch (row.rowNum) {
        case 1:
          if (day.am) {
            this.detailsDTOList.push({
              am: 1,
              depId: this.rowData.deptId,
              weekNo: day.weekNo,
              label: day.label,
              rgstTypeId: this.rowData.registertypeId,
              id: this.rowData.id,
              utyDate: day.utyDate,
              rgstId: this.rowData.id
            });
            if (day.isTrue) {
              day.isTrue = false;
            }
          } else {
            const existingAmIndex = this.detailsDTOList.findIndex(item => item.label === day.label && item.id === day.id);
            this.detailsDTOList[existingAmIndex].amLimit = null;
            delete this.detailsDTOList[existingAmIndex].am;
            day.am = null;
            if (day.pm === null && day.night === null) {
              day.isTrue = true;
            }
          }
          this.addItem(day.label, day.id)
          console.log(this.detailsDTOList)
          break;
        case 2 :

          if (day.pm) {
            this.detailsDTOList.push({
              pm: 1,
              depId: this.rowData.deptId,
              weekNo: day.weekNo,
              label: day.label,
              rgstTypeId: this.rowData.registertypeId,
              id: this.rowData.id,
              utyDate: day.utyDate,
              rgstId: this.rowData.id
            });
            if (day.isTrue) {
              day.isTrue = false;
            }
          } else {
            const existingPmIndex = this.detailsDTOList.findIndex(item =>
                item.label === day.label && item.id === day.id
            );
            this.detailsDTOList[existingPmIndex].pmLimit = null;
            delete this.detailsDTOList[existingPmIndex].pm;
            day.pm = null;
            if (day.am === null && day.night === null) {
              day.isTrue = true;
            }
          }
          this.addItem(day.label, day.id)
          console.log(this.detailsDTOList)
          break

        case 3 :
          if (day.night) {
            this.detailsDTOList.push({
              night: 1,
              depId: this.rowData.deptId,
              weekNo: day.weekNo,
              label: day.label,
              rgstTypeId: this.rowData.registertypeId,
              id: this.rowData.id,
              utyDate: day.utyDate,
              rgstId: this.rowData.id
            });
            if (day.isTrue) {
              day.isTrue = false;
            }
          } else {
            const existingNightIndex = this.detailsDTOList.findIndex(item =>
                item.label === day.label && item.id === day.id);
            this.detailsDTOList[existingNightIndex].nightLimit = null;
            delete this.detailsDTOList[existingNightIndex].night;
            day.night = null;
            if (day.am === null && day.pm === null) {
              day.isTrue = true;
            }
          }
          this.addItem(day.label, day.id)
          console.log(this.detailsDTOList)
          break
      }
    },
    handleInputChange(row, day) {
      console.log(row, day)
      switch (row.rowNum) {
        case 4:
          this.detailsDTOList.push({
            amLimit: parseInt(day.amLimit),
            depId: this.rowData.deptId,
            weekNo: day.weekNo,
            label: day.label,
            rgstTypeId: this.rowData.registertypeId,
            id: this.rowData.id,
            utyDate: day.utyDate,
            rgstId: this.rowData.id
          })
          this.addItem(day.label, day.id)
          console.log(this.detailsDTOList)
          break;
        case 5:
          this.detailsDTOList.push({
            pmLimit: parseInt(day.pmLimit),
            depId: this.rowData.deptId,
            weekNo: day.weekNo,
            label: day.label,
            rgstTypeId: this.rowData.registertypeId,
            id: this.rowData.id,
            utyDate: day.utyDate,
            rgstId: this.rowData.id
          })
          this.addItem(day.label, day.id)
          console.log(this.detailsDTOList)
          break
        case 6:
          this.detailsDTOList.push({
            nightLimit: parseInt(day.nightLimit),
            depId: this.rowData.deptId,
            weekNo: day.weekNo,
            label: day.label,
            rgstTypeId: this.rowData.registertypeId,
            id: this.rowData.id,
            utyDate: day.utyDate,
            rgstId: this.rowData.id
          })
          this.addItem(day.label, day.id)
          console.log(this.detailsDTOList)
          break

        case 7:
          this.detailsDTOList.push({
            limitRestrict: parseInt(day.limitRestrict),
            depId: this.rowData.deptId,
            weekNo: day.weekNo,
            label: day.label,
            rgstTypeId: this.rowData.registertypeId,
            id: this.rowData.id,
            utyDate: day.utyDate,
            rgstId: this.rowData.id
          })
          this.addItem(day.label, day.id)
          console.log(this.detailsDTOList)
          break
        case 8:
          this.detailsDTOList.push({
            limitNo: parseInt(day.limitNo),
            depId: this.rowData.deptId,
            weekNo: day.weekNo,
            label: day.label,
            rgstTypeId: this.rowData.registertypeId,
            id: this.rowData.id,
            utyDate: day.utyDate,
            rgstId: this.rowData.id
          })
          this.addItem(day.label, day.id)
          console.log(this.detailsDTOList)
          break
        case 9:
          this.detailsDTOList.push({
            netLimit: parseInt(day.netLimit),
            depId: this.rowData.deptId,
            weekNo: day.weekNo,
            label: day.label,
            rgstTypeId: this.rowData.registertypeId,
            id: this.rowData.id,
            utyDate: day.utyDate,
            rgstId: this.rowData.id
          })
          this.addItem(day.label, day.id)
          console.log(this.detailsDTOList)
          break

        case 10:
          this.detailsDTOList.push({
            otherLimit: parseInt(day.otherLimit),
            depId: this.rowData.deptId,
            weekNo: day.weekNo,
            label: day.label,
            rgstTypeId: this.rowData.registertypeId,
            id: this.rowData.id,
            utyDate: day.utyDate,
            rgstId: this.rowData.id
          })
          this.addItem(day.label, day.id)
          console.log(this.detailsDTOList)
          break
      }
    },
    handleInputFocus(row, day) {
      const index = this.detailsDTOList.findIndex(item =>
          item.label === day.label && item.id === day.id
      );
      const targetObj = this.detailsDTOList[index];
      const propsToSet = ['limitRestrict', 'limitNo', 'netLimit', 'otherLimit'];
      const arr = ['amLimit', 'pmLimit', 'nightLimit'];
      propsToSet.forEach(item => {
        if (targetObj.hasOwnProperty(item) && isNaN(targetObj[item])) {
          delete targetObj[item]
          day[item] = null;
          this.addItem(targetObj.label, day.id)
        }
      })
      arr.forEach(item => {
        if (targetObj.hasOwnProperty(item) && isNaN(targetObj[item])) {
          delete targetObj[item]
          day[item] = null;
          this.addItem(targetObj.label, day.id)
        }
      })

      if ([7, 8, 9, 10].includes(row.rowNum)) return;

      const safeNumber = (value) => {
        if (value === "" || value === null || value === undefined) return 0;
        const num = Number(value);
        return isNaN(num) ? 0 : num;
      };


      if (index !== -1) {

        const amLimit = safeNumber(targetObj.amLimit);
        const pmLimit = safeNumber(targetObj.pmLimit);
        const nightLimit = safeNumber(targetObj.nightLimit);
        const totalLimit = amLimit + pmLimit + nightLimit;

        if (totalLimit === 0) {
          arr.forEach(item => {
            delete targetObj[item];
          })
        }


        propsToSet.forEach(prop => {
          if (totalLimit === 0) {
            // 如果 totalLimit 是 0，删除这些字段
            targetObj[prop] = 0;
            day[prop] = null;
          } else {
            // 否则正常赋值
            targetObj[prop] = totalLimit;
            day[prop] = totalLimit;
          }
        });
        this.addItem(targetObj.label, day.id)
      }
    },
    async handleClickRow(row, column, cell, event) {
      this.$set(this, 'clickedCol', column.property) // 强制响应式
      this.$set(this, 'clickedRow', this.tableData2.indexOf(row))
      console.log()
      this.tableData4 = [];
      const data = this.detailsDTOList.find(item => item.label === column.label && item.id === row.id)
      if (!data) return;
      const date = dayjs().format('YYYY-MM-DD');
      const res = await getDoctorDateList({date: date, rgstId: data.id});
      this.tableData4 = res.data.map(item => {
        item.beinTime = item.beinTime.split(" ")[1]
        item.endTime = item.endTime.split(" ")[1]
        item.netB = item.netB === '0' ? '否' : '是'
        item.state = this.rowData.dutyStatus === 1 ? item.status === '1' ? '有效' : '无效' : '无效'
        item.limitNo = 1
        item.limitRestrict = 1
        item.timeSpan = item.timeSpan === 0 ? '全天' : item.timeSpan === 1 ? '上午' : item.timeSpan === 2 ? '下午' :
            item.timeSpan === 3 ? '晚班' : item.timeSpan === 4 ? '上下午' : item.timeSpan === 5 ? '下午晚班' :
                item.timeSpan === 6 ? '上午晚班' : '未知时段';
        return item;
      });
      console.log(res)
    },

    handleRowDoubleClick(row) {
      this.dateColumns.forEach(item => {
        item.am = null;
        item.pm = null;
        item.night = null;
        item.prop = null;
        item.night = null;
        item.amLimit = null;
        item.pmLimit = null;
        item.nightLimit = null;
        item.limitRestrict = null;
        item.limitNo = null;
        item.netLimit = null;
        item.otherLimit = null;
        item.id = row.id;
      })
      this.rowData = {...this.rowData, ...row};
      this.editDeptOrDoctor = {...row};
      const targetObjects = this.detailsDTOList.filter(item => item.id === row.id);
      targetObjects.forEach(item => {
        Object.keys(item).forEach(key => {
          if (item[key] === null || item[key] === 0) {
            delete item[key];
          }
        });

        // 3. 处理dateColumns
        const date = this.dateColumns.filter(item2 =>
            item.id === item2.id && item2.label === item.label
        );

        date.forEach(item3 => {
          // 转换布尔值
          item3.am = item.am === 1;
          item3.pm = item.pm === 1;
          item3.night = item.night === 1;

          // 赋值限额字段
          item3.amLimit = item.amLimit;
          item3.pmLimit = item.pmLimit;
          item3.nightLimit = item.nightLimit;
          item3.limitRestrict = item.limitRestrict;
          item3.limitNo = item.limitNo;
          item3.netLimit = item.netLimit;
          item3.otherLimit = item.otherLimit;
        });
      });

      console.log(targetObjects)
      this.editDialogVisible = true;
    },

    async getDoctorList() {
      if (this.doctorOptions.length > 1) return;
      const res = await getDoctorList()
      this.doctorOptions = res.data.map(item => {
        return {id: item.id, fullName: item.fullName}
      })
      console.log(res, 'resresresres')
    },

    async getDeptList() {
      if (this.deptOptions.length > 1) return;
      const res = await getDeptList();
      this.deptOptions = res.data.map(item => {
        return {id: item.id, deptName: item.deptName}
      })
    },

    async getDataByDeptId(event) {
      const isClearEvent = event && (event === 'clear' || event.type === 'clear');
      const res = await getActiveList({
        deptId: this.selDeptOrDoctor.deptId == null ? null : this.selDeptOrDoctor.deptId,
        doctorId: this.selDeptOrDoctor.doctorId == null ? null : this.selDeptOrDoctor.doctorId,
        state:1,
        schedulingB:0
      });

      this.tableData2 = res.data
      if (this.tableData2.length < 0) return;
      for (const val of this.detailsDTOList) {
        const index = this.detailsDTOList.findIndex(item =>
            item.label === val.label && item.id === val.id
        );

        if (index !== -1) {
          this.detailsDTOList[index] = val;
        } else {
          this.detailsDTOList.push(val);
        }

        const item = this.detailsDTOList.find(item =>
            item.label === val.label && item.id === val.id
        );
        // 其他业务逻辑...
        const timeSlots = [];
        if (item.am === 1) timeSlots.push('上午');
        if (item.pm === 1) timeSlots.push('下午');
        if (item.night === 1) timeSlots.push('晚上');
        const isAllDay = item.am === 1 && item.pm === 1 && item.night === 1;
        const rowIndex = this.tableData2.findIndex(item => item.id === val.id);
        this.$set(this.tableData2[rowIndex], item.label, isAllDay ? '全天' : timeSlots.join(''));
        this.addItem(val.label, val.id);
      }
      /*if (!isClearEvent) {
        this.processData();
        const sourceDate1 = new Date(this.rowData.startTime)
        this.generateDateColumns(sourceDate1);
        const schedulingData = await getSchedulingDtail({id: this.rowData.id});
        console.log(schedulingData)
        //this.schedulingDtailEcho(schedulingData.data.detailsRespVOList);
      }*/
    },

    async getDataByDoctor(event) {
      const isClearEvent = event && (event === 'clear' || event.type === 'clear');
      const res = await getActiveList({
        deptId: this.selDeptOrDoctor.deptId == null ? null : this.selDeptOrDoctor.deptId,
        doctorId: this.selDeptOrDoctor.doctorId == null ? null : this.selDeptOrDoctor.doctorId,
        state:1,
        schedulingB:0
      });
      this.tableData2 = res.data
      for (const val of this.detailsDTOList) {
        const index = this.detailsDTOList.findIndex(item =>
            item.label === val.label && item.id === val.id
        );

        if (index !== -1) {
          this.detailsDTOList[index] = val;
        } else {
          this.detailsDTOList.push(val);
        }

        const item = this.detailsDTOList.find(item =>
            item.label === val.label && item.id === val.id
        );
        // 其他业务逻辑...
        const timeSlots = [];
        if (item.am === 1) timeSlots.push('上午');
        if (item.pm === 1) timeSlots.push('下午');
        if (item.night === 1) timeSlots.push('晚上');
        const isAllDay = item.am === 1 && item.pm === 1 && item.night === 1;
        const rowIndex = this.tableData2.findIndex(item => item.id === val.id);
        this.$set(this.tableData2[rowIndex], item.label, isAllDay ? '全天' : timeSlots.join(''));
        this.addItem(val.label, val.id);
      }
      /*if (!isClearEvent) {
        this.processData();
        const sourceDate1 = new Date(this.rowData.startTime)
        this.generateDateColumns(sourceDate1);
        const schedulingData = await getSchedulingDtail({id: this.rowData.id});
        this.schedulingDtailEcho(schedulingData.data.detailsRespVOList);
      }*/
    },


    async updateDateColumns(val) {
      const startTime = new Date(this.rowData.startTime);
      let endTime = new Date(this.rowData.endTime);

      if (endTime < startTime) {
        endTime = new Date(startTime.getFullYear(), startTime.getMonth() + 1, 1);
        this.rowData.endTime = endTime.toISOString().split('T')[0]; // 格式化为YYYY-MM-DD
      }

      try {
        await withLoading(this, '处理中...')(async () => {
          if (val === null) {
            this.dateColumns = [];
            return;
          }

          // 清理数据
          this.tableData2.forEach(row => {
            Object.keys(row).forEach(key => {
              if (!isNaN(key) && key !== "" && !key.includes('.')) {
                row[key] = null;
              }
            });
          });

          this.detailsDTOList = [];
          this.dateColumns = [];
          this.tableData2 = [];

          // 获取数据
          const res = await getActiveList({state:1,schedulingB:0});
          this.tableData2 = res.data;

          // 处理合并逻辑
          this.processData();

          // 延迟生成日期列（保持原逻辑）
          await new Promise(resolve => {
            setTimeout(async () => {
              this.generateDateColumns(new Date(val));
              resolve();
            }, 1000);
          });

          this.$message.success("时间列生成完成");
        });
      } catch (error) {
        console.error("生成失败:", error);
        this.$message.error("时间列生成失败");

      } finally {
        // 强制表格重新布局（适配图片中的动态列）
        this.$nextTick(() => {
          this.$refs.tableRef?.doLayout();
        });
      }
    },


    processData() {
      const positions = [];
      let pos = 0;
      // 深拷贝并排序数据（关键修改）
      const sortedData = [...this.tableData2].sort((a, b) => a.deptId - b.deptId);
      sortedData.forEach((item, index) => {
        if (index === 0) {
          positions.push(1);
          pos = 0;
          return;
        }
        if (item.deptId === sortedData[index - 1].deptId) {
          positions[pos] += 1;
          positions.push(0);
        } else {
          positions.push(1);
          pos = index;
        }
      });

      this.spanConfig = positions;
    },

    objectSpanMethod({row, column, rowIndex, columnIndex}) {
      if (column.property === "deptName") {
        const span = this.spanConfig[rowIndex];
        return {
          rowspan: span > 0 ? span : 0,
          colspan: span > 0 ? 1 : 0
        };
      }
      // 其他列保持正常显示
      return {rowspan: 1, colspan: 1};
    },

    generateDateColumns(date) {
      const weekDays = ['日', '一', '二', '三', '四', '五', '六'];

      // 统一使用dayjs处理日期
      const baseDate = dayjs(date).startOf('day');

      if (this.selectedValue === 0) {
        // 周排班 - 生成7天数据
        this.dateColumns = Array.from({ length: 7 }, (_, i) => {
          const currentDate = baseDate.add(i, 'day');
          return this.generateDateItem(currentDate, weekDays);
        });

        // 设置结束时间
        this.rowData.endTime = this.dateColumns[6].utyDate;
      } else {
        // 月排班 - 生成当月所有天数数据
        const daysInMonth = baseDate.startOf('month').daysInMonth();

        this.dateColumns = Array.from({ length: daysInMonth }, (_, i) => {
          const currentDate = baseDate.startOf('month').add(i, 'day');
          return this.generateDateItem(currentDate, weekDays);
        });
      }

      // 更新表格
      this.$nextTick(() => {
        this.$refs.tableRef?.doLayout();
        this.processData();
      });
    },

// 统一的日期项生成方法
    generateDateItem(currentDate, weekDays) {
      const weekday = weekDays[currentDate.day()];

      return {
        prop: currentDate.format('YYYY-MM-DD'),
        label: this.selectedValue === 0 ?
            `${currentDate.month() + 1}月${currentDate.date()}日` :
            String(currentDate.date()),
        weekday: `周${weekday}`,
        weekNo: currentDate.day() === 0 ? 7 : currentDate.day(),
        am: null,
        pm: null,
        night: null,
        amLimit: null,
        pmLimit: null,
        nightLimit: null,
        limitRestrict: null,
        limitNo: null,
        netLimit: null,
        otherLimit: null,
        isTrue: true,
        number: null,
        utyDate: currentDate.format('YYYY-MM-DD')
      };
    },


    async loadData() {
      const res = await getSchedulingData({
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        state: this.numericValue == null ? null : this.numericValue,
        selectedValue: this.selectedValue == null ? null : this.selectedValue
      })
      if (res.code === 200) {
        this.tableData = res.data.content.map(item => ({
          ...item,
          startTime: item.startTime ? dayjs(item.startTime).format('YYYY-MM-DD HH:mm:ss') : null,
          endTime: item.endTime ? dayjs(item.endTime).format('YYYY-MM-DD HH:mm:ss') : null,
          dutyMentName: parseInt(item.dutyMent)
        }));
        this.pageNum = res.data.pageNum
        this.pageSize = res.data.pageSize
        this.totalSize = res.data.totalSize
      } else {
        this.$message.error(res.message)
      }
    },


    // headers commond
    async handleCommand(command) {
      this.numericValue = command === 'a' ? 1 : command === 'b' ? 0 : command === 'c' ? 2 : null;
      this.DropDownedName = command === 'a' ? '已审' : command === 'b' ? '待审' : command === 'c' ? '作废' : '全部';
      const res = await getSchedulingData({
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        state: this.numericValue == null ? null : this.numericValue,
        selectedValue: this.selectedValue == null ? null : this.selectedValue
      })
      if (res.code === 200) {
        this.tableData = res.data.content.map(item => ({
          ...item,
          username: this.userInfo.username,
          startTime: item.startTime ? item.startTime.split(' ')[0] : null,
          endTime: item.endTime ? item.endTime.split(' ')[0] : null,
          dutyMentName: item.dutyMent === "1" ? "临时" : "长期",
          state: item.dutyStatus === 0 ? "待审" : item.dutyStatus === 1 ? "已审" : "作废"
        }));
        this.pageNum = res.data.pageNum
        this.pageSize = res.data.pageSize
        this.totalSize = res.data.totalSize
      }
    },


    async feetHandClick(i) {
      // i event
      switch (i) {
        case 0:
          await withLoading(this, '数据加载中...')(async () => {
            const res = await getActiveList({state:1,schedulingB:0});
            this.tableData2 = res.data.filter(item => item.state === 1);
            this.processData();
            const sourceDate = new Date(this.rowData.startTime)
            this.generateDateColumns(sourceDate);
            this.schedulingDialogVisible = true;
          });
          break;
        case 1:
          if (!this.rowData?.id) return this.$message.warning("请先选择排班表再进行修改!")
          if (this.rowData.dutyStatus === 2) return this.$message.warning("该排班表已作废!")
          if (new Date(this.rowData.endTime) < new Date()) return this.$message.warning("该排班表已过期!")
          await withLoading(this, '数据加载中...')(async () => {
            const res2 = await getActiveList({state:1,schedulingB:0});
            this.tableData2 = res2.data;
            this.selectedValue = this.rowData.dutyMode;
            this.processData();
            const sourceDate1 = new Date(this.rowData.startTime)
            //this.generateDateColumns(sourceDate1);
            const schedulingData = await getSchedulingDtail({id: this.rowData.id});
            this.state = 1;
            this.schedulingDtailEcho(schedulingData.data.detailsRespVOList);
            this.schedulingDialogVisible = true;
          });
          break;

        case 2:
          if (this.rowData.id == null) return this.$message.warning("请先选择排班表再进行审批！");
          if (this.rowData.dutyStatus === 2) return this.$message.warning("该排班表已作废!");
          try {
            await this.$confirm(`确定要审核通过 ${this.rowData.name} 吗？`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            });
            await withLoading(this, '审核处理中...')(async () => {
              const res3 = await checkScheduling({id: this.rowData.id, status: 1});
              if (res3.code === 200) {
                await this.loadData();
                return this.$message.success(`审核 ${this.rowData.name} 成功`);
              } else {
                this.$message.error(res.message)
              }
              this.$message.error(`审核 ${this.rowData.name} 失败`);
            });
          } catch (error) {
            // 用户点击了取消或关闭弹窗
            return this.$message.info(`已取消对${this.rowData.name}的审核操作`);
          }
          break;

        case 3:
          if (this.rowData.id == null) return this.$message.warning("请先选择排班表再进行作废!");
          try {
            await this.$confirm(`确定要作废 ${this.rowData.name} 吗?`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            });
            await withLoading(this, '作废处理中...')(async () => {
              const res4 = await checkScheduling({id: this.rowData.id, status: 2});
              if (res4.code === 200) {
                await this.loadData();
                return this.$message.success(`作废${this.rowData.name}成功`);
              } else {
                this.$message.error(res.message)
              }
            });
          } catch (error) {
            return this.$message.info(`已取消对${this.rowData.name}的作废操作`);
          }
          break;
      }
    },
    schedulingDtailEcho(list) {
      list.forEach(val => {
        const rowIndex = this.tableData2.findIndex(
            item => item.deptId === val.depId && item.id === val.rgstId
        );
        if (rowIndex < 0) {
          this.tableData2 = [];
          return;
        }
        const rowData = this.tableData2[rowIndex]
        const newVal = {
          ...val,
          label: val.dateNo.toString(),
          id: rowData.id,
          rgstId: rowData.id
        };
        this.detailsDTOList.push(newVal)
        let result = [];
        if (val.am === 1) result.push("上午");
        if (val.pm === 1) result.push("下午");
        if (val.night === 1) result.push("晚上");
        this.$set(this.tableData2[rowIndex], val.dateNo, result.length < 3 ? result.join("") : '全天');
      })
    },

    async handleRowDblClick(row) {
      this.rowData = {...this.rowData, ...row};
      const res2 = await getActiveList({state:1,schedulingB:0});
      this.tableData2 = res2.data
      this.processData();
      const sourceDate1 = new Date(this.rowData.startTime)
      this.selectedValue = row.dutyMode;
      this.generateDateColumns(sourceDate1);
      if (row.id == null) return this.$message.warning("请先选择排班表再进行修改!")
      const schedulingData = await getSchedulingDtail({id: row.id});
      this.schedulingDtailEcho(schedulingData.data.detailsRespVOList);
      this.state = 3;
      this.schedulingDialogVisible = true;
    },

    handledbRow(row, column, event) {
      console.log(row)
      this.rowData = {...this.rowData, ...row};
      this.rowEditData = {...this.rowData, ...row};
      this.generateDateColumns(new Date(this.rowData.startTime))
    },
    // col 里面包含了表头字段和名称，list 是表格数据
    columnWidth(col, list) {
      let prop = col.prop, lab = col.lab;
      let width = 40; // 设定一个最小值
      let maxlenStr = ""; // 最长字符串
      for (let info of list) {
        if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
      }
      width = Math.max(width, len(lab), len(maxlenStr));
      // 表格自带的内边距(20px) 自调
      return width + 24; // 这里加了 12px
      function len(str) {
        // 实际分配长度可根据需要自行调整
        let length = 12;
        for (const char of str + "") {
          // 英文小写字符 8px
          if ("a" <= char && char <= "z") length += 8;
          // 英文大写字符 8px
          else if ("A" <= char && char <= "Z") length += 8;
          // 中文字符 28px
          else if (char >= "\u4e00" && char <= "\u9fa5") length += 28;
          // 其他 8px
          else length += 12;
        }
        return length;
      }
    },

    handleSelectionChange(val) {
      console.log(val);
    },
    //分页
    //每页条数改变触发
    handleSizeChange(val) {
      this.pageSize = val;
      this.pageNum = 1;
      this.loadData();
    },
    //当前条数改变触发
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val;
      this.loadData();
    },
    handleDateChange() {
      // 禁用日期选择器
      this.isDatePickerDisabled = true;

      // 2秒后恢复
      setTimeout(() => {
        this.isDatePickerDisabled = false;
      }, 2000);

      // 调用原有的更新逻辑
      this.updateDateColumns();
    },
    updateWindowWidth() {
      this.windowWidth = window.innerWidth - 288;
    },
    getScheduleType(timeSlots) {
      const hasMorning = timeSlots.includes('上午');
      const hasAfternoon = timeSlots.includes('下午');
      const hasNight = timeSlots.includes('晚上');

      if (hasMorning && hasAfternoon && hasNight) {
        return 0; // 全天
      } else if (hasMorning && !hasAfternoon && !hasNight) {
        return 1; // 上午
      } else if (!hasMorning && hasAfternoon && !hasNight) {
        return 2; // 下午
      } else if (!hasMorning && !hasAfternoon && hasNight) {
        return 3; // 晚班
      } else if (hasMorning && hasAfternoon && !hasNight) {
        return 4; // 上下午
      } else if (!hasMorning && hasAfternoon && hasNight) {
        return 5; // 下午晚班
      } else if (hasMorning && !hasAfternoon && hasNight) {
        return 6; // 上午晚班
      } else {
        return -1; // 未知类型（根据实际情况可能需要处理）
      }
    },
    getColumnWidth(label, prop, tableData) {
      const minWidth = 100;
      const padding = 30; // 增加边距缓冲
      const contentList = tableData.map(item => item?.[prop] ?? '');

      // 计算所有内容宽度（包括表头）
      const widths = [...contentList, label].map(text => {
        const str = String(text || '');
        return this.getTextWidth(str) + padding;
      });

      return Math.max(minWidth, ...widths);
    },

    // 精确计算文本宽度（使用Canvas）
    getTextWidth(text, fontSize = 14) {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      ctx.font = `${fontSize}px Microsoft YaHei`;
      return ctx.measureText(text).width;
    },

    labelHead(h, {column, $index}) {
      let l = column.label.length;
      let f = 12;
      column.minWidth = f * (l + 5); //加上一个文字长度
      return h("div", {class: "table-head", style: {width: "100%"}}, [
        column.label,
      ]);
    },

    safeGetMappedValue(col, row, type) {

      const hiddenProps = new Set([
        'usedfrquId', 'sdoseCnt', 'prdCnt', 'prdDays', 'medcWayId', 'tcmCnt',
        'selfProe', 'skintstRslt', 'remark', 'remarks', 'rxDosCnt',
      ]);

      if (hiddenProps.has(col.prop)) {
        return ''; // 直接返回空字符串，不显示
      }
      // 1. 检查数据有效性
      const rawValue = row[col.prop];
      if (rawValue === null || rawValue === undefined) return ' ';

      // 2. 检查映射数组
      const mapArray = this[col.op];
      if (!col.op || !Array.isArray(mapArray)) return rawValue;

      // 3. 执行映射
      const matched = mapArray.find(item => item.id == rawValue);
      return matched?.label || rawValue;
    },
  }
}
</script>

<style lang="less" scoped>
.homeTable {
  flex: 1;
  min-height: 0; /* 关键：允许flex容器收缩 */
  overflow: auto; /* 确保内容溢出时显示滚动条 */
  width: 100%; /* 确保容器宽度填满父元素 */
  position: relative; /* 建立新的定位上下文 */
}

.homeTable .el-table {
  width: 100% !important;
  /* 移除height:100%以避免内部高度计算问题 */
  min-width: 1350px; /* 保持表格最小宽度与内联样式一致 */
}

.homeTable ::v-deep .el-table__body-wrapper {
  overflow-x: auto !important; /* 强制水平滚动 */
}

.homeTable ::v-deep .el-table__header-wrapper {
  overflow-x: hidden !important; /* 防止表头出现双滚动条 */
}

::v-deep .el-table .highlight-cell {
  background: #0b5baf !important;
  color: white !important;
}

/* 覆盖行悬停干扰 */
.el-table--enable-row-hover .el-table__body tr:hover td {
  background: inherit !important;
}

.highlight-cell {
  background: #000000 !important;
  color: white;
}

.highlight-cell {
  background-color: #f0f7ff !important; /* 高亮颜色 */
}

.cell-highlight-table .el-table__body td {
  transition: all 0.2s;
}

.cell-highlight-table .el-table__body td:hover {
  background: #ecf5ff !important;
  box-shadow: inset 0 0 0 1px #409eff;
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 15px;
}

.filter-item {
  display: flex;
  align-items: center;
}

.filter-label {
  margin-right: 8px;
  white-space: nowrap;
}

.divider-line {
  height: 1px;
  background-color: #ebeef5;
  margin: 10px 0;
}

/* 双表格容器布局 */
.dual-table-container {
  display: flex;
  gap: 12px;
  width: 100%;
}

.main-table {
  transition: width 0.3s ease;
}

.detail-table {
  width: 30%;
  flex-shrink: 0;
}

/* 底部控制栏布局 */
.dialog-footer {
  margin-top: 10px;
}

.footer-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-items {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.action-items {
  display: flex;
  align-items: center;
  gap: 15px;
}

.action-buttons {
  margin-left: 15px;
}

/* 调整对话框样式 */
.schedule-dialog {
  max-width: 1200px;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .dual-table-container {
    flex-direction: column;
  }

  .main-table, .detail-table {
    width: 100% !important;
  }

  .footer-controls {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .action-items {
    width: 100%;
    justify-content: space-between;
  }
}

.weekday {
  font-size: 12px;
  color: #ffffff;
}

.week-row {
  color: #39648f;
  font-weight: bold;
  display: block;
}

.compact-cell {
  padding: 3px !important;
  line-height: 1.3;
  font-size: 12px;
}

/* 表头样式 */
::v-deep .el-table__header th {
  background-color: #39648f;
  color: white;
}

.custom-table-style /deep/ .el-table__header th {
  background-color: #39648f !important;
  color: #fff !important;
  font-weight: bold !important;
  font-size: 14px !important;
  border-color: #39648f !important;
}

/* 或者使用 ::v-deep (推荐) */
.custom-table-style::v-deep .el-table__header th:hover {
  background-color: #2d5275 !important;
}

/* 表格边框 */
.custom-table-style::v-deep .el-table--border {
  border-color: #39648f;
}

.custom-table-style::v-deep .el-table--border th,
.custom-table-style::v-deep .el-table--border td {
  border-color: #39648f;
}


.filter-row {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}

.filter-item {
  display: flex;
  align-items: center;
  margin-right: 20px;
}

.filter-label {
  min-width: 60px;
  text-align: right;
  margin-right: 10px;
  font-size: 14px;
  color: #606266;
}

/* 保持与Element UI一致的间距 */
.el-date-editor.el-input,
.el-select {
  width: 150px;
}

.divider-line {
  height: 1px;
  background-color: #e4e7ed; /* Element UI 默认边框色 */
  margin: 12px 0; /* 上下间距 */
}

/deep/ .el-dropdown {
  font-size: 14px;
  cursor: pointer;
}

/deep/ .el-dropdown:hover {
  font-weight: bold;
  color: #66b1ff;
}

/deep/ .el-icon--right {
  // background-color: #66b1ff;
}

/deep/ .el-popper[x-placement^=bottom] {
  margin-top: 0;
}

.siting {
  height: 90vh; /* 让容器占满整个视口高度 */
  display: flex;
  flex-direction: column;

  .main-icon {
    display: flex;
    align-items: center;
    padding: 12px;
    line-height: 70px;

    .main-icon-a {
      width: 200px;
      // background-color: #00557f;
    }

    .main-icon-b {
      margin-left: 28px;
    }

    // c
    .main-icon-c {
      display: flex;
      margin-left: -60px;

      /deep/ [data-v-2bacc09b] .el-color-picker__icon, .el-input[data-v-2bacc09b], .el-textarea[data-v-2bacc09b] {
        width: 80%;
      }
    }
  }

  .feet {

    margin-left: 24px; /* 向右移动12px（原12px基础上增加） */
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: flex-start;
  }


  .main-icon-zzgl {
    display: flex;
    align-items: center; /* 保持内部元素垂直居中 */
    margin-left: 12px; /* 原有间距 */
    white-space: nowrap; /* 防止自身内容换行 */
  }

  /* 弹框头部样式优化 */

  /deep/ .el-dialog__header {
    background-color: #39648f; /* 深蓝色背景 */
    padding: 12px 20px;
    border-radius: 4px 4px 0 0;
  }

  /deep/ .el-dialog__title {
    color: #fff !important; /* 强制白色标题 */
    font-size: 16px;
    font-weight: bold;
    letter-spacing: 1px;
  }

  /deep/ .el-dialog__headerbtn {
    top: 10px; /* 调整关闭按钮位置 */
  }

  /deep/ .el-dialog__headerbtn .el-dialog__close {
    color: #fff; /* 默认白色关闭图标 */
    font-size: 18px;
  }

  /deep/ .el-dialog__headerbtn .el-dialog__close:hover {
    color: #a3d0ff !important; /* 悬停时浅蓝色 */
  }
}
</style>